<template>
  <div :class="styles['exam-container']">
    <!-- 考试专用头部 -->
    <header :class="styles['exam-header']">
      <div :class="styles['exam-header-left']">
        <div :class="styles['logo']">
          <img src="/exam-ai-logo.svg" alt="Exam AI" :class="styles['logo-img']">
          <span :class="styles['logo-text']">Exam AI</span>
        </div>
      </div>
      <div :class="styles['exam-header-center']">
        <h1 :class="styles['exam-title']">{{ exam.title }}</h1>
      </div>
      <div :class="styles['exam-header-right']">
        <div :class="styles['user-info']">
          <span :class="styles['user-name']">{{ user?.name || user?.username }}</span>
          <span :class="[styles['user-role'], styles['student-badge']]">学生</span>
        </div>
      </div>
    </header>

    <div :class="styles['exam-content']">
      <div :class="styles['exam-view']">
        <!-- 考试头部信息卡片 -->
        <div :class="styles['exam-header-card']">
          <div :class="styles['exam-info']">
            <div :class="styles['exam-title-section']">
              <h2 :class="styles['exam-title-text']">{{ exam.title }}</h2>
              <div :class="styles['exam-meta']">
                <span :class="styles['meta-item']">
                  <span :class="styles['meta-icon']">📊</span>
                  总分: {{ exam.totalScore }}分
                </span>
                <span :class="styles['meta-item']">
                  <span :class="styles['meta-icon']">📝</span>
                  题目: {{ exam.questions.length }}道
                </span>
                <span :class="styles['meta-item']">
                  <span :class="styles['meta-icon']">⏱️</span>
                  时长: {{ exam.duration }}分钟
                </span>
              </div>
            </div>
          </div>

          <div :class="styles['exam-controls']">
            <!-- 倒计时器 -->
            <div :class="[styles['timer-card'], { [styles['time-warning']]: remainingTime < 300 }]">
              <div :class="styles['timer-icon']">⏰</div>
              <div :class="styles['timer-content']">
                <div :class="styles['timer-label']">剩余时间</div>
                <div :class="styles['timer-time']">{{ formattedTime }}</div>
              </div>
            </div>

            <!-- 进度指示器 -->
            <div :class="styles['progress-indicator']">
              <div :class="styles['progress-header']">
                <span :class="styles['progress-label']">答题进度</span>
                <span :class="styles['progress-count']">{{ answeredCount }}/{{ exam.questions.length }}</span>
              </div>
              <div :class="styles['progress-bar']">
                <div :class="styles['progress-fill']" :style="{ width: progressPercentage + '%' }"></div>
              </div>
              <div :class="styles['progress-percentage']">{{ progressPercentage }}%</div>
            </div>
          </div>
        </div>

        <!-- 题目导航 -->
        <div :class="styles['question-nav']">
          <div :class="styles['nav-header']">
            <h3 :class="styles['nav-title']">题目导航</h3>
            <span :class="styles['nav-subtitle']">点击快速跳转</span>
          </div>
          <div :class="styles['nav-grid']">
            <button v-for="(question, index) in exam.questions" :key="question.id" :class="[
              styles['nav-item'],
              { [styles['answered']]: answers[question.id] && answers[question.id] !== '' },
              { [styles['current']]: currentQuestionIndex === index }
            ]" @click="scrollToQuestion(index)">
              {{ index + 1 }}
            </button>
          </div>
        </div>

        <!-- 考试题目列表 -->
        <div :class="styles['question-list']">
          <div v-for="(question, index) in exam.questions" :key="question.id" :class="styles['question-card']"
            :ref="el => questionRefs[index] = el">
            <div :class="styles['question-header']">
              <div :class="styles['question-info']">
                <span :class="styles['question-index']">{{ index + 1 }}</span>
                <span :class="styles['question-type']">{{ getQuestionTypeName(question.type) }}</span>
                <span :class="styles['question-score']">{{ question.score }}分</span>
              </div>
              <div :class="styles['question-actions']">
                <button :class="styles['action-btn']" @click="markQuestion(index)">
                  <span :class="styles['action-icon']">🏷️</span>
                  标记
                </button>
              </div>
            </div>

            <h3 :class="styles['question-title']">{{ question.title }}</h3>

            <!-- 单选题 -->
            <div v-if="question.type === 'single'" :class="styles['options-container']">
              <div v-for="(option, optIndex) in question.options" :key="optIndex" :class="[
                styles['option-item'],
                { [styles['selected']]: answers[question.id] === option.key }
              ]" @click="selectOption(question.id, option.key)">
                <div :class="styles['option-radio']">
                  <div :class="[styles['radio-circle'], { [styles['checked']]: answers[question.id] === option.key }]">
                  </div>
                </div>
                <div :class="styles['option-content']">
                  <span :class="styles['option-key']">{{ option.key }}.</span>
                  <span :class="styles['option-text']">{{ option.text }}</span>
                </div>
              </div>
            </div>

            <!-- 多选题 -->
            <div v-if="question.type === 'multiple'" :class="styles['options-container']">
              <div v-for="(option, optIndex) in question.options" :key="optIndex" :class="[
                styles['option-item'],
                { [styles['selected']]: isOptionSelected(question.id, option.key) }
              ]" @click="toggleOption(question.id, option.key)">
                <div :class="styles['option-checkbox']">
                  <div
                    :class="[styles['checkbox-square'], { [styles['checked']]: isOptionSelected(question.id, option.key) }]">
                    <span v-if="isOptionSelected(question.id, option.key)" :class="styles['checkmark']">✓</span>
                  </div>
                </div>
                <div :class="styles['option-content']">
                  <span :class="styles['option-key']">{{ option.key }}.</span>
                  <span :class="styles['option-text']">{{ option.text }}</span>
                </div>
              </div>
            </div>

            <!-- 判断题 -->
            <div v-if="question.type === 'judge'" :class="styles['options-container']">
              <div :class="[
                styles['option-item'],
                styles['judge-option'],
                { [styles['selected']]: answers[question.id] === 'true' }
              ]" @click="selectOption(question.id, 'true')">
                <div :class="styles['option-radio']">
                  <div :class="[styles['radio-circle'], { [styles['checked']]: answers[question.id] === 'true' }]">
                  </div>
                </div>
                <div :class="styles['option-content']">
                  <span :class="styles['option-icon']">✅</span>
                  <span :class="styles['option-text']">正确</span>
                </div>
              </div>
              <div :class="[
                styles['option-item'],
                styles['judge-option'],
                { [styles['selected']]: answers[question.id] === 'false' }
              ]" @click="selectOption(question.id, 'false')">
                <div :class="styles['option-radio']">
                  <div :class="[styles['radio-circle'], { [styles['checked']]: answers[question.id] === 'false' }]">
                  </div>
                </div>
                <div :class="styles['option-content']">
                  <span :class="styles['option-icon']">❌</span>
                  <span :class="styles['option-text']">错误</span>
                </div>
              </div>
            </div>

            <!-- 填空题 -->
            <div v-if="question.type === 'fill'" :class="styles['answer-input']">
              <input v-model="answers[question.id]" :class="styles['input-field']" placeholder="请输入答案" type="text" />
            </div>

            <!-- 简答题 -->
            <div v-if="question.type === 'short_answer'" :class="styles['answer-textarea']">
              <textarea v-model="answers[question.id]" :class="styles['textarea-field']" placeholder="请简要回答（建议50-100字）"
                rows="4"></textarea>
              <div :class="styles['word-count']">
                <span :class="styles['count-text']">已输入 {{ getWordCount(answers[question.id]) }} 字</span>
              </div>
            </div>

            <!-- 论述题 -->
            <div v-if="question.type === 'essay'" :class="styles['answer-textarea']">
              <textarea v-model="answers[question.id]" :class="styles['textarea-field']" placeholder="请详细论述（建议200-500字）"
                rows="6"></textarea>
              <div :class="styles['word-count']">
                <span :class="styles['count-text']">已输入 {{ getWordCount(answers[question.id]) }} 字</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 考试操作按钮 -->
        <div :class="styles['action-buttons']">
          <button :class="[styles['action-btn'], styles['secondary']]" @click="saveDraft">
            <span :class="styles['btn-icon']">💾</span>
            保存草稿
          </button>
          <button :class="[styles['action-btn'], styles['primary']]" @click="submitExam">
            <span :class="styles['btn-icon']">📤</span>
            提交试卷
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAuthStore } from '@/stores/auth'
import styles from '@/styles/student/exam.module.css'

const router = useRouter()
const authStore = useAuthStore()

const user = computed(() => authStore.user)

// 模拟考试数据
const exam = ref({
  id: 'exam-001',
  title: '2025年春季学期期末考试',
  totalScore: 100,
  duration: 120, // 考试时长(分钟)
  questions: [
    {
      id: 'q1',
      type: 'single',
      title: '以下哪个不是JavaScript的数据类型?',
      score: 10,
      options: [
        { key: 'A', text: 'Number' },
        { key: 'B', text: 'String' },
        { key: 'C', text: 'Boolean' },
        { key: 'D', text: 'Function' }
      ]
    },
    {
      id: 'q2',
      type: 'multiple',
      title: 'Vue.js的核心特性包括哪些?',
      score: 20,
      options: [
        { key: 'A', text: '数据绑定' },
        { key: 'B', text: '组件系统' },
        { key: 'C', text: '路由管理' },
        { key: 'D', text: '状态管理' }
      ]
    },
    {
      id: 'q3',
      type: 'judge',
      title: 'Vue 3使用Proxy实现响应式系统',
      score: 10
    },
    {
      id: 'q4',
      type: 'fill',
      title: 'HTTP状态码200表示______',
      score: 10
    },
    {
      id: 'q5',
      type: 'short_answer',
      title: '简述MVC和MVVM的区别',
      score: 20
    },
    {
      id: 'q6',
      type: 'essay',
      title: '请详细论述前端工程化的重要性和实现方式',
      score: 30
    }
  ]
})

// 学生答案
const answers = ref({})
// 剩余时间(秒)
const remainingTime = ref(exam.value.duration * 60)
// 当前题目索引
const currentQuestionIndex = ref(0)
// 题目引用
const questionRefs = ref([])

// 格式化显示时间
const formattedTime = computed(() => {
  const minutes = Math.floor(remainingTime.value / 60)
  const seconds = remainingTime.value % 60
  return `${minutes}:${seconds.toString().padStart(2, '0')}`
})

// 计算已答题数量
const answeredCount = computed(() => {
  return Object.keys(answers.value).filter(key => {
    const answer = answers.value[key]
    return answer !== undefined && answer !== null && answer !== ''
  }).length
})

// 计算进度百分比
const progressPercentage = computed(() => {
  return Math.round((answeredCount.value / exam.value.questions.length) * 100)
})

// 获取题目类型名称
const getQuestionTypeName = (type) => {
  const typeMap = {
    single: '单选题',
    multiple: '多选题',
    judge: '判断题',
    fill: '填空题',
    short_answer: '简答题',
    essay: '论述题'
  }
  return typeMap[type] || '未知类型'
}

// 选择选项（单选）
const selectOption = (questionId, optionKey) => {
  answers.value[questionId] = optionKey
}

// 切换选项（多选）
const toggleOption = (questionId, optionKey) => {
  if (!answers.value[questionId]) {
    answers.value[questionId] = []
  }
  const currentAnswers = Array.isArray(answers.value[questionId]) ? answers.value[questionId] : []
  const index = currentAnswers.indexOf(optionKey)
  if (index > -1) {
    currentAnswers.splice(index, 1)
  } else {
    currentAnswers.push(optionKey)
  }
  answers.value[questionId] = currentAnswers
}

// 检查选项是否被选中（多选）
const isOptionSelected = (questionId, optionKey) => {
  const currentAnswers = answers.value[questionId]
  return Array.isArray(currentAnswers) && currentAnswers.includes(optionKey)
}

// 标记题目
const markQuestion = (index) => {
  ElMessage.success(`已标记第${index + 1}题`)
}

// 滚动到指定题目
const scrollToQuestion = (index) => {
  currentQuestionIndex.value = index
  if (questionRefs.value[index]) {
    questionRefs.value[index].scrollIntoView({
      behavior: 'smooth',
      block: 'start'
    })
  }
}

// 获取字数统计
const getWordCount = (text) => {
  if (!text) return 0
  return text.replace(/\s/g, '').length
}

// 计时器
let timer = null

onMounted(() => {
  // 开始考试计时
  timer = setInterval(() => {
    remainingTime.value--
    if (remainingTime.value <= 0) {
      clearInterval(timer)
      submitExam()
    }
  }, 1000)
})

onBeforeUnmount(() => {
  if (timer) {
    clearInterval(timer)
  }
})

// 提交考试
const submitExam = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要提交试卷吗？提交后将无法修改答案。',
      '确认提交',
      {
        confirmButtonText: '确定提交',
        cancelButtonText: '继续答题',
        type: 'warning',
      }
    )

    clearInterval(timer)
    ElMessage.success('试卷提交成功！')
    router.push('/student/exam-result')
  } catch {
    // 用户取消提交
  }
}

// 保存草稿
const saveDraft = () => {
  ElMessage.success('草稿保存成功！')
}
</script>
